import { reqAddOrUpdateShopCart, reqUpdateCheckedByid,reqCartList, reqDeleteCart } from "@/api"

const state = {
    cartList:[]
}
const mutations = {
    cartList(state,data){
        state.cartList = data
    }
}
const actions = {
    // 获取购物车列表
    async getCartList({commit}){
        let result = await reqCartList()
        if(result.code == 200) {
            commit('cartList',result.data)
        }
    },
    async addOrUpdateShopCart({commit},{skuId,skuNum}){
        let result = await reqAddOrUpdateShopCart(skuId,skuNum)
        if(result.code == 200) {
            return "ok"
        }else {
            return Promise.reject(new Error('addOrUpdateShopCart Fail !'))
        }
    },
    // 修改购物车产品的选中状态
    async updateCheckedByid({commit},{skuId,isChecked}){
        let result = await reqUpdateCheckedByid(skuId,isChecked)
        if(result.code == 200) {
            return "ok"
        }else {
            return Promise.reject(new Error('addOrUpdateShopCart Fail !'))
        }
    },

    // 删除购物车中的商品
    async deleteCart({commit},skuId){
        let result = await reqDeleteCart(skuId)
        if(result.code == 200) {
            return "ok"
        }else {
            return Promise.reject(new Error('addOrUpdateShopCart Fail !'))
        }
    } ,
    // 删除全部选中商品
    deleteAllCart({dispatch, getters}){
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ?
                dispatch("deleteCart",item.skuId) : ""

            PromiseAll.push(promise)
        });

        return Promise.all(PromiseAll)
    },
    // 全选全不选
    updateAllCartIsChecked({dispatch,state},isChecked){
        console.log(1)
        let PromiseAll = []
        state.cartList[0].cartInfoList.forEach((item)=>{
            let promise = dispatch("updateCheckedByid",{
                skuId:item.skuId,
                isChecked
            })

            PromiseAll.push(promise)
        })

        return Promise.all(PromiseAll)
    }
}
const getters = {
    cartList(state){
        //console.log(state.cartList[0].cartInfoList)
        return state.cartList[0] || {}  
    }
}

export default {
    state,mutations,actions,getters
}